/**
 * 
 */
package com.srini.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.srini.pojos.LoggedInUser;
import com.srini.pojos.Role;
import com.srini.pojos.UserInfo;
import com.srini.util.ConnectionUtil;
import com.vssr.persist.DataBaseWriter;
import com.vssr.persist.DomainObject;

/**
 * @author A200171
 * 
 */
public class AddUserServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		System.out.println("Adding user....");

		String empName = req.getParameter("empName");
		String email = req.getParameter("email");
		String travelAllowance = req.getParameter("trallowance");
		String foodAllowance = req.getParameter("foodallowance");
		String role = req.getParameter("role");
		String managerId = req.getParameter("managerId");
		String message = "";
		Connection conn = new ConnectionUtil().getConnection();
		String query = "select * from USERTABLE where username = '" + empName
				+ "'";
		List userList = null;
		try {
			userList = DomainObject.getDBRecords(new LoggedInUser(), query,
					conn);
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (userList == null || userList.isEmpty()) {
			LoggedInUser user = new LoggedInUser();
			user.setUserName(empName);
			user.setPassword(empName);

			user.setTrAllowance(travelAllowance);
			user.setFoodAllowance(foodAllowance);
			user.setCreatedOn(Calendar.getInstance().getTime().toString());
			if (managerId != null) {
				user.setManagerId(Integer.valueOf(managerId));
			}

			UserInfo userInfo = new UserInfo();
			userInfo.setEmail(email);
			user.setUserInfo(userInfo);
			Role roleObj = new Role();
			roleObj.setRole(role);

			user.setRole(roleObj);
			DataBaseWriter.save(user);
			message = "User successfully created.";
		} else {
			message = "Error::User with this name already exist. Please choose other.";
		}
		req.setAttribute("message", message);
		req.setAttribute("currentPage", "admin");
		req.getRequestDispatcher("/home.jsp").forward(req, resp);
	}
}
